/**
 * 作者：陈文斌 on 2019/1/8.
 * 邮箱：chen_wennbin@163.com
 * 版本：v1.0
 */

import 'package:flutter/material.dart';
import 'package:crm/constant/constant.dart';
import 'package:crm/viewModel/ClientManager/client_manager_view_model.dart';
import 'package:crm/model/ClientManager/contact_info_model.dart';
import 'package:crm/view/Tile/tile_space_between.dart';
import 'package:crm/view/Tile/list_tile_text_field.dart';

/// 全部添加中的联系人列表
class ContactsInfoEditSection extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _ContactsInfoEditSectionState();
}

class _ContactsInfoEditSectionState extends State<ContactsInfoEditSection> {
  final TextStyle _titleStyle = TextStyle(
    color: AppColors.DetailTextColor,
    fontSize: AppFontSizes.Font15,
    fontFamily: AppFontFamilies.PingFangSC,
    fontWeight: FontWeight.w500,
  );
  List<ContactInfoModel> _contactsList = List<ContactInfoModel>();

  @override
  void initState() {
    _contactsList.add(ContactInfoModel.fromJson({}));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    /// 继续添加联系人按钮
    Widget _addContactButton = Container(
      height: 44,
      child: Material(
        color: Colors.white,
        child: InkWell(
          onTap: () {
            setState(() {
              _contactsList.add(ContactInfoModel.fromJson({}));
            });
          },
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Icon(
                Icons.add,
                size: 20,
                color: AppColors.DetailTextColor,
              ),
              Text(
                '继续添加',
                style: _titleStyle,
              ),
            ],
          ),
        ),
      ),
    );

    /// 保存按钮
    Widget _saveButton = Container(
      width: AppScreen.setWidth(318),
      height: 40,
      margin: EdgeInsets.fromLTRB(
        AppScreen.setWidth(28),
        100,
        AppScreen.setWidth(29),
        20,
      ),
      decoration: BoxDecoration(
        color: AppColors.MainColor,
        borderRadius: BorderRadius.circular(20),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(20),
        child: MaterialButton(
          onPressed: () {
            /// 保存联系人
            ClientManagerVM().saveContactsInfo(context, _contactsList);
          },
          child: Text(
            '保存',
            style: TextStyle(
              color: Colors.white,
              fontSize: AppFontSizes.Font17,
              fontFamily: AppFontFamilies.PingFangSC,
            ),
          ),
        ),
      ),
    );

    return Container(
      // 计算高度，避免父组件SingleChildScrollView可滑动区域高度计算冲突
      height: (45.0 * 6 + 36) * _contactsList.length + 40 + 144 + 20 + 44 + 10,
      child: ListView.builder(
        // 阻止滑动
        physics: const NeverScrollableScrollPhysics(),
        // _contactsList.length个联系人区域 + 1个添加、保存按钮区域
        itemCount: _contactsList.length + 1,
        itemBuilder: (context, i) {
          if (i < _contactsList.length) {
            // item 在_contactsList.length范围内返回ContactInfoEditSection
            ContactInfoModel _contactInfo = _contactsList[i];
            return ContactInfoEditSection(
              title: '联系人${i + 1}',
              contactInfo: _contactInfo,
              deleteCallback: (c) {
                setState(() {
                  _contactsList.removeAt(i);
                });
              },
            );
          } else {
            // item 不在_contactsList.length范围内，返回添加、保存按钮区域
            return Column(
              children: <Widget>[
                Padding(padding: EdgeInsets.only(top: 10)),
                // 添加按钮
                _addContactButton,
                // 保存按钮
                _saveButton,
              ],
            );
          }
        },
      ),
    );
  }
}

/// 其中一个联系人信息编辑列表
class ContactInfoEditSection extends StatefulWidget {
  final String title;
  final ContactInfoModel contactInfo;
  final Function deleteCallback;

  @override
  ContactInfoEditSection({
    Key key,
    this.title = '',
    this.contactInfo,
    this.deleteCallback,
  }) : super(key: key);

  State<StatefulWidget> createState() => _ContactInfoEditSectionState();
}

class _ContactInfoEditSectionState extends State<ContactInfoEditSection> {
  final TextStyle _titleStyle = TextStyle(
    color: AppColors.DetailTextColor,
    fontSize: AppFontSizes.Font15,
    fontFamily: AppFontFamilies.PingFangSC,
    fontWeight: FontWeight.w500,
  );

  final FocusNode _nameFocusNode = FocusNode();
  final FocusNode _positionFocusNode = FocusNode();
  final FocusNode _phoneFocusNode = FocusNode();
  final FocusNode _telephoneFocusNode = FocusNode();
  final FocusNode _QQAccountFocusNode = FocusNode();
  final FocusNode _mailFocusNode = FocusNode();

  /// 创建一个联系人对象
  ContactInfoModel _contactInfo;

  /// 联系人单个属性编辑栏
  Widget ContactInfoListTextFieldTile(
    String title,
    String content,
    FocusNode focusNode,
    FocusNode nextFocusNode, {
    bool requiredVisible = true,
    TextInputAction textInputAction = TextInputAction.next,
    ValueChanged<String> onChange,
  }) {
    return ListTileTextField(
      requiredVisible: requiredVisible,
      title: Text(
        title,
        style: _titleStyle,
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
      ),
      content: content,
      textInputAction: textInputAction,
      focusNode: focusNode,
      onEditingComplete: () {
        FocusScope.of(context).requestFocus(nextFocusNode);
      },
      onChanged: onChange,
    );
  }

  @override
  Widget build(BuildContext context) {
    _contactInfo = widget.contactInfo ?? ContactInfoModel.fromJson({});

    Widget _headerSection = TileSpaceBetween(
      title: Text(widget.title),
      subtitle: Container(
        width: 45,
        child: Material(
          color: AppColors.PageBackgroundColor,
          child: InkWell(
            onTap: () {
              if (widget.deleteCallback != null) {
                widget.deleteCallback(_contactInfo);
              }
            },
            child: Text(
              '删除',
              style: TextStyle(
                color: AppColors.MainColor,
                fontSize: AppFontSizes.Font13,
                fontFamily: AppFontFamilies.PingFangSC,
                fontWeight: FontWeight.w500,
              ),
              textAlign: TextAlign.right,
            ),
          ),
        ),
      ),
    );

    return Column(
      children: <Widget>[
        _headerSection,
        ContactInfoListTextFieldTile(
          '姓名',
          _contactInfo.name ?? '',
          _nameFocusNode,
          _positionFocusNode,
          onChange: (name) {
            _contactInfo.name = name;
          },
          requiredVisible: false,
        ),
        ContactInfoListTextFieldTile(
          '职位',
          _contactInfo.position ?? '',
          _positionFocusNode,
          _phoneFocusNode,
          onChange: (position) {
            _contactInfo.position = position;
          },
        ),
        ContactInfoListTextFieldTile(
          '手机',
          _contactInfo.phone ?? '',
          _phoneFocusNode,
          _telephoneFocusNode,
          onChange: (phone) {
            _contactInfo.phone = phone;
          },
          requiredVisible: false,
        ),
        ContactInfoListTextFieldTile(
          '座机',
          _contactInfo.telephone ?? '',
          _telephoneFocusNode,
          _QQAccountFocusNode,
          onChange: (telephone) {
            _contactInfo.telephone = telephone;
          },
        ),
        ContactInfoListTextFieldTile(
          'QQ',
          _contactInfo.QQaccount ?? '',
          _QQAccountFocusNode,
          _mailFocusNode,
          onChange: (QQAccount) {
            _contactInfo.QQaccount = QQAccount;
          },
        ),
        ContactInfoListTextFieldTile(
          '邮箱',
          _contactInfo.mail ?? '',
          _mailFocusNode,
          FocusNode(),
          textInputAction: TextInputAction.done,
          onChange: (mail) {
            _contactInfo.mail = mail;
          },
        ),
      ],
    );
  }
}
